package com.example.project.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.project.dao.UserDao;
import com.example.project.entity.User;
import com.example.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;

    @Override
    public String getToken(User user, long time) {
        Date start = new Date();//token起始时间
        long currentTime = System.currentTimeMillis() + time;
        Date end = new Date(currentTime);//token结束时间
        String token = "";
        token = JWT.create()
                .withAudience(user.getId().toString()) //存放接收方的信息
                .withIssuedAt(start)//token开始时间
                .withExpiresAt(end)//token存活截止时间
                .sign(Algorithm.HMAC256(user.getPassword()));//加密
        return token;
    }

    @Override
    public User findUser(Long id) {
        return userDao.findById(id);
    }

    @Override
    public User findUser(String name) {
        return userDao.findByName(name);
    }

    @Override
    public void saveUser(User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        log.info(user.toString());
        userDao.saveUser(user);
    }
}
